﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using SalaryChannel.OrderWebService;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.Text.RegularExpressions;
using System.IO;

namespace SalaryChannel
{
    public partial class DeviceOrder : UserControl
    {
        private OrderServiceClient _orderService = null;
        private static OperationContext _orderPC = null;

        public OrderServiceClient OrderService
        {
            get
            {
                if (_orderService == null)
                {
                    _orderService = new OrderServiceClient();

                    OperationContext.Current = new OperationContext((IContextChannel)_orderService.InnerChannel);
                    MessageHeader header = MessageHeader.CreateHeader("uafcztga", "",ServiceInstance.UserName);
                    OperationContext.Current.OutgoingMessageHeaders.Add(header);
                    header = MessageHeader.CreateHeader("xufasft", "", ServiceInstance.Password);
                    OperationContext.Current.OutgoingMessageHeaders.Add(header);
                    _orderPC = OperationContext.Current;
                }
                else
                {
                    OperationContext.Current = _orderPC;
                }
                return _orderService;
            }
            set { _orderService = value; }
        }
        public DeviceOrder()
        {
            InitializeComponent();

            OrderService.AddStockCompleted += new EventHandler<AddStockCompletedEventArgs>(OrderService_AddStockCompleted);
            OrderService.GetDeviceStockCompleted += new EventHandler<GetDeviceStockCompletedEventArgs>(OrderService_GetDeviceStockCompleted);
            OrderService.GetOrderHisCompleted += new EventHandler<GetOrderHisCompletedEventArgs>(OrderService_GetOrderHisCompleted);
            OrderService.CreateDeivceCompleted += new EventHandler<CreateDeivceCompletedEventArgs>(OrderService_CreateDeivceCompleted);
            OrderService.GetStockManageHisCompleted += new EventHandler<GetStockManageHisCompletedEventArgs>(OrderService_GetStockManageHisCompleted);

            SHPreBtn.MouseLeftButtonDown += new MouseButtonEventHandler(SHPreBtn_MouseLeftButtonDown);
            SHNextBtn.MouseLeftButtonDown += new MouseButtonEventHandler(SHNextBtn_MouseLeftButtonDown);
            SHPageTB.KeyDown += new KeyEventHandler(SHPageTB_KeyDown);

            SHStartDate.Text = DateTime.Today.ToString();
            SHEndDate.Text = SHStartDate.Text;
            HisStartDate.Text = SHStartDate.Text;
            HisEndDate.Text=SHStartDate.Text;

            RpStartDate.Text = SHStartDate.Text;
            RpEndDate.Text = SHStartDate.Text;


            OrderService.GetOrderStockCompleted += new EventHandler<GetOrderStockCompletedEventArgs>(OrderService_GetOrderStockCompleted);
            OrderService.OrderDeviceForUserCompleted += new EventHandler<OrderDeviceForUserCompletedEventArgs>(OrderService_OrderDeviceForUserCompleted);
            OrderService.CancelUserOrderCompleted += new EventHandler<CancelUserOrderCompletedEventArgs>(OrderService_CancelUserOrderCompleted);
            OrderService.ExportHisByFileCompleted += new EventHandler<ExportHisByFileCompletedEventArgs>(OrderService_ExportHisByFileCompleted);
            PhoneRegex = new Regex(DataHelper.PhoneNumRegexString);

            OrderService.GetOrderReportCompleted += new EventHandler<GetOrderReportCompletedEventArgs>(OrderService_GetOrderReportCompleted);
        }

       
       
        static Regex PhoneRegex;
       

        public void Initiallize()
        {
            BigTab.SelectedIndex = 0;
            ClearStockPage();
            ClearStockMngPage();
            ClearOrderHisPage();
            ClearOrderPage();
            RpTable = null;
            RpGrid.ItemsSource = null;

            if (App.IsAuth(14))
            {

                StockPage.Visibility = Visibility.Visible;
                StockHisPage.Visibility = Visibility.Visible;
                HisCancelBtn.Visibility = Visibility.Visible;
            }
            else{
               
                StockPage.Visibility = Visibility.Collapsed;
                StockHisPage.Visibility = Visibility.Collapsed;
                HisCancelBtn.Visibility = Visibility.Collapsed;
            }
        }

        private void BigTabControl_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            TabControl tab=(sender as TabControl);
            if(tab.Tag ==null)
            {
                tab.Tag ="BigTab";
                return;
            }

           
            if (tab.SelectedItem != null)
            {
                this.RemarkTB.Text = string.Empty;
            }
            if (tab.SelectedItem.Equals(StockPage))
            {
                //ClearStockPage();
            }
        }

        #region 终端预约

        void ClearOrderPage()
        {
            this.OrderDeviceNameTB.Text = string.Empty;
            this.OrderUserTB.Text = string.Empty;
            if (OrderGrid.ItemsSource == null)
            {
                OrderQueryBtn_Click(null, null);
            }
            
        }

        private void OrderQueryBtn_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                OrderService.GetOrderStockAsync(OrderDeviceNameTB.Text);
                OrderQueryBtn.IsEnabled = false;
                OrderLoading.Show();
            }
            catch 
            {
                App.MessageBox.ShowDialog("连接服务器失败，请稍后再试");
            }
        }

        private void OrderBtn_Click(object sender, RoutedEventArgs e)
        {
            lock (this)
            {
                if (OrderGrid.SelectedItem == null)
                {
                    App.MessageBox.ShowDialog("请先选择一个终端");
                    return;
                }

                if (PhoneRegex.IsMatch(OrderUserTB.Text))
                {
                    App.MessageBox.ShowDialog("预约后无法撤销，请确认！", new Action(DoOrderCallBack), Title.Warning);
                   
                }
                else
                {
                    App.MessageBox.ShowDialog("用户号码非法");
                } 
            }
        }


        void DoOrderCallBack()
        {
            try
            {
                OrderService.OrderDeviceForUserAsync(
                                (OrderGrid.SelectedItem as VW_DeviceStock).Device_ID, OrderUserTB.Text,
                                App.CurrentUser.UserID, RemarkTB.Text);
                OrderBtn.IsEnabled = false;
                OrderLoading.Show();
            }
            catch
            {

                App.MessageBox.ShowDialog("连接服务器失败，请稍后再试");
            }
        }

        void OrderService_OrderDeviceForUserCompleted(object sender, OrderDeviceForUserCompletedEventArgs e)
        {
            try
            {
                if (e.Result == 0)
                {
                    OrderQueryBtn_Click(null, null);
                    App.MessageBox.ShowDialog("预约成功");
                }
                else if (e.Result == 1)
                {
                    App.MessageBox.ShowDialog("预约失败，此终端已无库存，请重新查询");
                }
                else if (e.Result == 2)
                {
                    App.MessageBox.ShowDialog("同一用户不能重复预约！");
                }
                else 
                {
                    App.MessageBox.ShowDialog("预约失败，请稍后再试");
                }
            }
            catch (Exception ex)
            {

                App.MessageBox.ShowDialog("预约失败，" + ex.Message);
            }
            finally
            {
                OrderBtn.IsEnabled = true;
                OrderLoading.Stop();
            }
        }

        void OrderService_GetOrderStockCompleted(object sender, GetOrderStockCompletedEventArgs e)
        {
            try
            {
                if (e.Result != null)
                {
                    OrderGrid.ItemsSource = e.Result;
                }
                else
                {
                    App.MessageBox.ShowDialog("查询失败，请稍后再试");
                }
            }
            catch (Exception ex)
            {
                App.MessageBox.ShowDialog("查询失败，" + ex.Message);
            }
            finally
            {
                OrderQueryBtn.IsEnabled = true;
                OrderLoading.Stop();
            }
        }

        #endregion

        #region 预约记录查询

        void ClearOrderHisPage()
        {
            this.HisGrid.ItemsSource = null;
            this.HisUserNumTB.Text = string.Empty;
            this.HisQueryBtn.IsEnabled = true;
            HisDownBtn.Visibility = Visibility.Collapsed;
            
        }

        private void HisQueryBtn_Click(object sender, RoutedEventArgs e)
        {
            if (!PhoneRegex.IsMatch(HisUserNumTB.Text) && !App.IsAuth(13))
            {
                App.MessageBox.ShowDialog("请正确输入用户号码");
                return;
            }
            try
            {
                DateTime start, end;
                
                try
                {
                    if (DateTime.Parse(HisStartDate.Text) > DateTime.Parse(HisEndDate.Text))
                    {
                        App.MessageBox.ShowDialog("开始日期不能大于结束日期");
                        return;
                    }

                    start = DateTime.Parse(HisStartDate.Text + " 00:00:00");
                    end = DateTime.Parse( HisEndDate.Text  + " 23:59:59");
                }
                catch (Exception ex)
                {
                    App.MessageBox.ShowDialog("日期格式非法," + ex.Message);
                    return;
                }

                OrderService.GetOrderHisAsync(HisUserNumTB.Text,start,end);
                HisQueryBtn.IsEnabled = false;
                HisLoading.Show();
            }
            catch 
            {

                App.MessageBox.ShowDialog("连接服务器失败，请稍后再试");
            }

        }

        void OrderService_GetOrderHisCompleted(object sender, GetOrderHisCompletedEventArgs e)
        {
            try
            {
                if (e.Result == null)
                {
                    App.MessageBox.ShowDialog("查询失败，请稍后再试");
                }
                else
                {
                    HisGrid.ItemsSource = e.Result;
                }
            }
            catch(Exception ex)
            {

                App.MessageBox.ShowDialog("查询失败，"+ ex.Message);
            }
            finally
            {
                HisLoading.Stop();
                HisQueryBtn.IsEnabled = true;
            }
        }

        private void HisCancelBtn_Click(object sender, RoutedEventArgs e)
        {
            if (HisGrid.SelectedItem == null)
            {
                App.MessageBox.ShowDialog("请先选择一条对预约工单");
                return;
            }
            if ((HisGrid.SelectedItem as VW_OrderHIS).Sts == "撤单")
            {
                App.MessageBox.ShowDialog("此工单已撤单！");
                return;
            }
            if (string.IsNullOrEmpty(RemarkTB.Text))
            {
                App.MessageBox.ShowDialog("请先输入备注");
                return;
            }

            App.MessageBox.ShowDialog("请确认预约终端未发货！", new Action(DoCancelCallBack), Title.Warning);
           
        }

        void DoCancelCallBack()
        {
            try
            {
                OrderService.CancelUserOrderAsync((HisGrid.SelectedItem as VW_OrderHIS).ID, 
                   string.Format("[{0}]{1},撤销：{2},{3} {4}",App.CurrentUser.UserID,App.CurrentUser.UserName,
                   RemarkTB.Text,DateTime.Now.ToShortDateString(), DateTime.Now.ToShortTimeString()));
                HisCancelBtn.IsEnabled = false;
                HisLoading.Show();
            }
            catch
            {

                App.MessageBox.ShowDialog("连接服务器失败，请稍后再试");
            }
        }


        void OrderService_CancelUserOrderCompleted(object sender, CancelUserOrderCompletedEventArgs e)
        {
            try
            {
                if (e.Result)
                {
                    App.MessageBox.ShowDialog("操作成功");
                }
                else
                {
                    App.MessageBox.ShowDialog("操作失败，请稍后再试");
                }
            }
            catch (Exception ex)
            {

                App.MessageBox.ShowDialog("操作失败，" + ex.Message);
            }
            finally
            {
                HisCancelBtn.IsEnabled = true;
                HisLoading.Stop();
            }
        }

        private void HisExportBtn_Click(object sender, RoutedEventArgs e)
        {

            string start, end;

            try
            {
                if (DateTime.Parse(HisStartDate.Text) > DateTime.Parse(HisEndDate.Text))
                {
                    App.MessageBox.ShowDialog("开始日期不能大于结束日期");
                    return;
                }
                start =  HisStartDate.Text;
                end =  HisEndDate.Text ;
            }
            catch (Exception ex)
            {
                App.MessageBox.ShowDialog("日期格式非法," + ex.Message);
                return;
            }

            try
            {
                OrderService.ExportHisByFileAsync(HisUserNumTB.Text, start, end);
                HisExportBtn.IsEnabled = false;
                HisLoading.Show();
            }
            catch
            {

                App.MessageBox.ShowDialog("连接服务器失败，请稍后再试");
            }

        }

        void OrderService_ExportHisByFileCompleted(object sender, ExportHisByFileCompletedEventArgs ee)
        {
            try
            {

                if (ee.Result == string.Empty)
                {
                    App.MessageBox.ShowDialog("没有查询到数据");
                }
                else if (ee.Result == "-1")
                {
                    App.MessageBox.ShowDialog("导出失败，请联系管理员");
                }
                else
                {
                    // System.Windows.Browser.HtmlPage.Window.Navigate(new Uri(ee.Result, UriKind.Relative), "_blank");
                    //(ee.Result);// new Uri(ee.Result, UriKind.Relative);
                    string uri = System.Windows.Browser.HtmlPage.Document.DocumentUri.AbsoluteUri;
                    //App.MessageBox.ShowDialog(uri);
                    if (!uri.ToLower().EndsWith("salary/"))
                    {
                        if (!uri.EndsWith("/'"))
                        {
                            uri = uri.Remove(uri.LastIndexOf('/') + 1) + ee.Result;
                        }
                    }
                    else
                    {
                        uri += ee.Result;
                    }
                    HisDownBtn.NavigateUri = new Uri(uri);

                    HisDownBtn.Visibility = Visibility.Visible;
                }

            }
            catch (Exception ex)
            {

                App.MessageBox.ShowDialog("导出异常，" + ex.Message);
            }
            finally
            {
                HisLoading.Stop();
                HisExportBtn.IsEnabled = true;
            }
        }

        
        #endregion


        #region 库存管理记录查询

        private int PageSize = 100;
        private int _sHPageIndex = 1;

        void ClearStockMngPage()
        {
            SHUserIDTB.Text = string.Empty;
            SHDeviceIDTB.Text = string.Empty;
            SHPageTB.Text = "1";
            SHGrid.ItemsSource = null;
        }


        public int SHPageIndex
        {
            get { return _sHPageIndex; }
            set
            {
                if (value != _sHPageIndex)
                {
                    if (value < 1) return;

                    _sHPageIndex = value;
                    SHPageTB.Text = value.ToString();
                    SHGoToPage();
                }
            }
        }


        bool SHCanQuery = true;
        void SHGoToPage()
        {
            if (!SHCanQuery)
            {
                return;
            }
            try
            {
                DateTime start, end;
             
                try
                {
                    if (DateTime.Parse(SHStartDate.Text) > DateTime.Parse(SHEndDate.Text))
                    {
                        App.MessageBox.ShowDialog("开始日期不能大于结束日期");
                        return;
                    }
                    start = DateTime.Parse(SHStartDate.Text +" 00:00:00");
                    end = DateTime.Parse(SHEndDate.Text + " 23:59:59");
                }
                catch (Exception ex)
                {
                    App.MessageBox.ShowDialog("日期格式非法," + ex.Message);
                    return;
                }
                
                int id = -1;
                if (!string.IsNullOrEmpty(SHDeviceIDTB.Text))
                {
                    if (!int.TryParse(SHDeviceIDTB.Text, out id))
                    {
                        App.MessageBox.ShowDialog("终端ID只能为整数");
                    }
                }
                OrderService.GetStockManageHisAsync(start, end, id, SHUserIDTB.Text, SHPageIndex, PageSize);
                SHCanQuery = false;
                SHLoading.Show();
            }
            catch (Exception ex)
            {

                App.MessageBox.ShowDialog("提交失败，" + ex.Message);
            }
            
        }

        void OrderService_GetStockManageHisCompleted(object sender, GetStockManageHisCompletedEventArgs e)
        {
            try
            {
                if (e.Result != null)
                {
                    SHGrid.ItemsSource = e.Result;
                }
                else
                {
                    App.MessageBox.ShowDialog("查询失败，请稍后再试");
                }
            }
            catch
            {

                App.MessageBox.ShowDialog("查询失败，请稍后再试");
            }
            finally
            {
                SHCanQuery = true;
                SHLoading.Stop();
            }
        }

        private void SHQueryBtn_Click(object sender, RoutedEventArgs e)
        {
            _sHPageIndex = -1;
            SHPageIndex = 1;
        }

        void SHNextBtn_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            if (SHGrid.ItemsSource != null)
            {
                if ((SHGrid.ItemsSource as List<VW_StockMngHis>).Count == PageSize)
                {
                    SHPageIndex++;
                }
            }
        }

        void SHPreBtn_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            if (SHPageIndex > 1)
            {
                SHPageIndex--;
            }
        }

        void SHPageTB_KeyDown(object sender, KeyEventArgs e)
        {
            int page = -1;
            if (int.TryParse(SHPageTB.Text, out page))
            {
                if (page >= 1)
                {
                    SHPageIndex = page;
                }
            }
        }

        #endregion

        #region 库存管理

        void ClearStockPage()
        {
            this.StockGrid.ItemsSource = null;
            this.RemarkTB.Text = string.Empty;
            this.StockDeviceNameTB.Text = string.Empty;
            this.StockNewName.Text = string.Empty;
            this.StockAddTB.Text = string.Empty;
        }

        
        private void StockQueryBtn_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                OrderService.GetDeviceStockAsync(this.StockDeviceNameTB.Text);
                this.StockQueryBtn.IsEnabled = false;
                this.StockLoading.Show();
            }
            catch 
            {
                App.MessageBox.ShowDialog("连接服务器失败");
            }
        }


        void OrderService_GetDeviceStockCompleted(object sender, GetDeviceStockCompletedEventArgs e)
        {
            try
            {
                if (e.Result == null)
                {
                    App.MessageBox.ShowDialog("查询失败，请稍后再试");
                }
                else
                {
                    this.StockGrid.ItemsSource = e.Result;

                }
            }
            catch (Exception ex)
            {
                App.MessageBox.ShowDialog("查询失败，" + ex.Message);
            }
            finally
            {
                StockLoading.Stop();
                StockQueryBtn.IsEnabled =true;
            }
        }

        /// <summary>
        /// 为终端追加库存
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void StockAddBtn_Click(object sender, RoutedEventArgs e)
        {
            if (StockGrid.SelectedItem == null)
            {
                App.MessageBox.ShowDialog("请先选择一个终端");
                return;
            }
            int add=0;
            if (int.TryParse(this.StockAddTB.Text, out add))
            {
                if (add == 0)
                {
                    App.MessageBox.ShowDialog("追加库存量不能为零");
                }
                else
                {
                    if (add < 0)
                    {
                        int h = DateTime.Now.Hour;
                        if (h >= 8 && h <= 18)
                        {
                            App.MessageBox.ShowDialog("不能在营业时间内追加负库存量");
                            return;
                        }
                        if ((StockGrid.SelectedItem as VW_DeviceStock).Stock + add < 0)
                        {
                            App.MessageBox.ShowDialog("库存量不能为负");
                            return;
                        }

                    }
                   

                    try
                    {
                        OrderService.AddStockAsync(App.CurrentUser.UserID,
                                        (StockGrid.SelectedItem as VW_DeviceStock).Device_ID, add, RemarkTB.Text);
                        StockAddBtn.IsEnabled = false;
                    }
                    catch 
                    {

                        App.MessageBox.ShowDialog("连接服务器失败");
                    }
                }

            }
            else
            {
                App.MessageBox.ShowDialog("追加库存量必须是整数");
            }

        }
        void OrderService_AddStockCompleted(object sender, AddStockCompletedEventArgs e)
        {
            try
            {
                if (e.Result)
                {
                    this.StockQueryBtn_Click(null, null);
                    App.MessageBox.ShowDialog("追加成功");
                }
                else
                {
                    App.MessageBox.ShowDialog("追加失败，请稍候再试");
                }
            }
            catch
            {

                App.MessageBox.ShowDialog("追加失败，请稍候再试");
            }
            finally
            {
                StockAddBtn.IsEnabled = true;
            }
        }

        /// <summary>
        /// 添加新终端
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void StockNewBtn_Click(object sender, RoutedEventArgs e)
        {

            if (string.IsNullOrEmpty(this.StockNewName.Text))
            {
                App.MessageBox.ShowDialog("请输入新增的终端名称");
                return;
            }
            try
            {
                OrderService.CreateDeivceAsync(App.CurrentUser.UserID, this.StockNewName.Text.Trim(),
                       this.RemarkTB.Text);
                this.StockAddBtn.IsEnabled = false;
            }
            catch
            {
                this.StockAddBtn.IsEnabled = true;
                App.MessageBox.ShowDialog("连接服务器失败");
            }
        }

        void OrderService_CreateDeivceCompleted(object sender, CreateDeivceCompletedEventArgs e)
        {
            try
            {
                if (e.Result==0)
                {
                    App.MessageBox.ShowDialog("添加成功");
                }
                else if (e.Result == 1)
                {
                    App.MessageBox.ShowDialog("不能重复添加");
                }
                else
                {
                    App.MessageBox.ShowDialog("添加失败,请稍候再试");
                }
            }
            catch (Exception ex)
            {

                App.MessageBox.ShowDialog("添加失败," + ex.Message);
            }
            finally
            {
                this.StockAddBtn.IsEnabled = true;
               
            }
        }

        #endregion

        #region 监控报表
        private void RpChannelOrderBtn_Click(object sender, RoutedEventArgs e)
        {
            string start, end;

            try
            {
                if (DateTime.Parse(RpStartDate.Text) > DateTime.Parse(RpEndDate.Text))
                {
                    App.MessageBox.ShowDialog("开始日期不能大于结束日期");
                    return;
                }

                start = RpStartDate.Text + " 00:00:00";
                end = RpEndDate.Text + " 23:59:59";
            }
            catch (Exception ex)
            {
                App.MessageBox.ShowDialog("日期格式非法," + ex.Message);
                return;
            }
            try
            {
                string area = App.CurrentUser.CountyCode;
                string channel = App.CurrentUser.ChannelID;
                string pq = App.CurrentUser.DistrictID;
                if (App.IsAuth(13))
                {
                    area = string.Empty;
                    channel = string.Empty;
                    pq = string.Empty;
                }
                else if (App.IsAuth(12))
                {
                    channel = string.Empty;
                    pq = string.Empty;
                }
                else if (App.IsAuth(11))
                {
                    channel = string.Empty;
                }
                OrderService.GetOrderReportAsync(ReportType.ChannelOrder, start, end,area,pq,channel,ReportType.ChannelOrder);
                RpIllgalOrderBtn.IsEnabled = false;
                RpChannelOrderBtn.IsEnabled = false;
                RpSaveBtn.IsEnabled = false;
                RpLoading.Show();
            }
            catch 
            {
                App.MessageBox.ShowDialog("连接服务器失败");
            }
        }

        private void RpIllgalOrderBtn_Click(object sender, RoutedEventArgs e)
        {
            string start, end;

            try
            {
                if (DateTime.Parse(RpStartDate.Text) > DateTime.Parse(RpEndDate.Text))
                {
                    App.MessageBox.ShowDialog("开始日期不能大于结束日期");
                    return;
                }

                start = RpStartDate.Text + " 00:00:00";
                end = RpEndDate.Text + " 23:59:59";
            }
            catch (Exception ex)
            {
                App.MessageBox.ShowDialog("日期格式非法," + ex.Message);
                return;
            }
            try
            {
                string area = App.CurrentUser.CountyCode;
                string channel = App.CurrentUser.ChannelID;
                string pq = App.CurrentUser.DistrictID;
                if (App.IsAuth(13))
                {
                    area = string.Empty;
                    channel = string.Empty;
                    pq = string.Empty;
                }
                if (App.IsAuth(13))
                {
                    area = string.Empty;
                    channel = string.Empty;
                    pq = string.Empty;
                }
                else if (App.IsAuth(12))
                {
                    channel = string.Empty;
                    pq = string.Empty;
                }
                else if (App.IsAuth(11))
                {
                    channel = string.Empty;
                }
                
                OrderService.GetOrderReportAsync(ReportType.IllgalOrder, start, end,
                    area,pq,channel, ReportType.IllgalOrder);
                RpIllgalOrderBtn.IsEnabled = false;
                RpChannelOrderBtn.IsEnabled = false;
                RpSaveBtn.IsEnabled = false;
                RpLoading.Show();
            }
            catch
            {
                App.MessageBox.ShowDialog("连接服务器失败");
            }
        }

        Silverlight.DataTable RpTable = null;
        void OrderService_GetOrderReportCompleted(object sender, GetOrderReportCompletedEventArgs e)
        {
            try
            {
                if (e.Result == null)
                {
                    App.MessageBox.ShowDialog("查询失败，请稍后再试");
                }
                else
                {
                     RpTable = Xml2Table.Convert(e.Result.TableNamek__BackingField,
                                   e.Result._columns, e.Result.XmlStringk__BackingField);
                     if (RpTable.Rows.Count == 0)
                    {
                        App.MessageBox.ShowDialog("没有查询到数据");
                        RpGrid.ItemsSource = null;
                        return;
                    }
                     RpGrid.ItemsSource = RpTable.GetBindableData(new Silverlight.Connector());

                }
            }
            catch (Exception ex)
            {

                App.MessageBox.ShowDialog("查询失败，" + ex.Message);
            }
            finally
            {
                RpIllgalOrderBtn.IsEnabled = true;
                RpChannelOrderBtn.IsEnabled = true;
                RpSaveBtn.IsEnabled = true;

                this.RpLoading.Stop();
            }
        }


        private void RpSaveBtn_Click(object sender, RoutedEventArgs e)
        {
            if (RpTable == null
                || RpTable.Rows.Count == 0)
            {
                App.MessageBox.ShowDialog("没有可以保存的数据");
                return;
            }

            try
            {
                SaveFileDialog dialog = new SaveFileDialog();
                dialog.Filter = "TXT文件|*.txt";
                if (dialog.ShowDialog().Value)
                {
                    using (StreamWriter writer = new StreamWriter(dialog.OpenFile(), System.Text.Encoding.Unicode))
                    {
                        string line = string.Empty;
                        foreach (Silverlight.DataColumn col in RpTable.Columns)
                        {
                            line += string.Format("\"{0}\"\t", col.ColumnName);
                        }
                        writer.WriteLine(line);

                        foreach (Silverlight.DataRow row in RpTable.Rows)
                        {
                            line = string.Empty;
                            foreach (Silverlight.DataColumn col in RpTable.Columns)
                            {
                                line += string.Format("\"{0}\"\t", row[col.ColumnName]);
                            }
                            writer.WriteLine(line);
                        }
                    }
                    App.MessageBox.ShowDialog("保存成功");
                }
            }
            catch (Exception ex)
            {

                App.MessageBox.ShowDialog("保存失败," + ex.Message);
            }
            


        }

        #endregion




    }
}
